//
//  JSBridgeImage.swift
//  ToBeBigFE
//
//  Created by mingo on 2020/2/13.
//  Copyright © 2020 com.example. All rights reserved.
//

import Foundation
import UIKit
import Photos

class JSBridgeImage : BridgeModuelBase {

    weak var viewController: WebViewController?
    fileprivate var pickerDelegate: PickerDelegate?

    init(viewController: WebViewController) {
        self.viewController = viewController
    }

    override func callFunc(_ funcName: String, callbackId: String, arg: [String : Any?]) {
        switch funcName {
        case "pickPhotos": pickPhotos(callbackId: callbackId, arg: arg)
        default: break
        }
    }
    
    private func pickPhotos(callbackId: String, arg: [String : Any?]) {
        guard let vc = self.viewController else { return }
        
        let picker = UIImagePickerController()
        picker.sourceType = .photoLibrary
        pickerDelegate = PickerDelegate()
        pickerDelegate?.jsbridgeImage = self
        pickerDelegate?.callbackId = callbackId
        picker.delegate = pickerDelegate!
        vc.present(picker, animated: true, completion: nil)
    }

}

fileprivate class PickerDelegate : NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    weak var jsbridgeImage: JSBridgeImage?
    var callbackId: String!
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        jsbridgeImage?.pickerDelegate = nil
        picker.dismiss(animated: true, completion: nil)
        
    
        let url = info[UIImagePickerController.InfoKey.referenceURL] as? URL
        let asset = info[UIImagePickerController.InfoKey.phAsset] as? PHAsset
        let type = asset?.mimeType()
        // callback给js
        jsbridgeImage?.callback(callbackId: callbackId, json: [
            "success": true,
            "type": type,
            "file": url?.absoluteString
        ])
    }
    
    
    // 出来用户取消的操作
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        jsbridgeImage?.pickerDelegate = nil
        picker.dismiss(animated: true, completion: nil)
        jsbridgeImage?.callback(callbackId: callbackId, json: [
            "success": false,
            "canceled": true
        ])
    }
    
}
